import os
import random
import uuid

from flask import Flask, session, render_template, redirect, Blueprint, request

from utils.getPublicData import getAllHourseInfoMap, getHourseInfoById, createHourseInfo, editHourseInfoById, \
    deleteHourseInfoById, getHourseCitysList, getHoursePriceData, getHourseInfoByCity, getAllHourseInfo
from utils.getPageData import *
import app


# Blueprint蓝图: 分模块组织管理
# 指定蓝图的url前缀
page_bp = Blueprint('page', __name__, url_prefix='/page', template_folder='templates')


@page_bp.route('/home', methods=['GET'])
def home():
    username = session.get('username')

    # TODO: 预测最贵房价
    predMaxHoursePrice = 15000
    # TODO: 预测最多城市
    predMostCity = '上海'

    # 数据
    hourseData = getAllHourseInfo()
    # TODO: 地图的数据
    # 标签数据
    total, maxPrice, mostHourseType, mostSaleStatus, titleText = getHomeTagsData(hourseData)
    # 各省房源个数
    cityRadarIndicator, cityRadarData = getHomeRadarData(hourseData)


    return render_template(
        'home.html',
        username=username,
        predMaxHoursePrice=predMaxHoursePrice,
        predMostCity=predMostCity,
        total=total,
        maxPrice=maxPrice,
        mostHourseType=mostHourseType,
        mostSaleStatus=mostSaleStatus,
        cityRadarIndicator=cityRadarIndicator[:20],
        cityRadarData=cityRadarData[:20],
    )

    # hourseData = getAllHourseInfoMap()[:5]
    #
    # # getHomeGeoCharData(hourseData)
    #
    # total, maxPrice, mostHourseType, mostSaleStatus = getHomeTagsData(hourseData)
    #
    # cityRadarIndicator, cityRadarData = getHomeRadarData(hourseData)
    #
    # return render_template(
    #     'home.html',
    #     username=username,
    #     total=total,
    #     maxPrice=maxPrice,
    #     mostHourseType=mostHourseType,
    #     mostSaleStatus=mostSaleStatus,
    #     cityRadarIndicator=cityRadarIndicator,
    #     cityRadarData=cityRadarData,
    # )


@page_bp.route('/search', methods=['GET', 'POST'])
def search():
    username = session.get('username')
    hourseData = getAllHourseInfo()
    if request.method == 'GET' or request.form['keyword'] == '':
        hourseList = [hourseData[random.randint(0, len(hourseData))] for i in range(10)]
        cityList = list(set([i.city for i in hourseList]))
    else:
        print(request.form['keyword'])
        hourseList = getSearchHourseDataByTitle(request.form['keyword'], hourseData)
        print(hourseList)
        # 显示过多页面会很卡
        if len(hourseList) > 20:
            hourseList = hourseList[:20]
        cityList = list(set([i.city for i in hourseList]))

    return render_template(
        'search.html',
        username=username,
        hourseList=hourseList,
        cityList=cityList,
    )


@page_bp.route('/table', methods=['GET', 'POST'])
def table():
    username = session.get('username')
    hourseData = getAllHourseInfo()
    # TODO: 分页处理
    hourseData = hourseData[:5]

    return render_template(
        'table.html',
        username=username,
        hourseData=hourseData
    )


@page_bp.route('/detail', methods=['GET', 'POST'])
def tableDetail():
    username = session.get('username')
    id = request.args.get('id')
    hourseInfo = getHourseInfoById(id)

    return render_template(
        'details.html',
        username=username,
        hourseInfo=hourseInfo,
    )


@page_bp.route('/addHourse', methods=['GET', 'POST'])
def addHourseInfo():
    username = session.get('username')
    if request.method == 'GET':
        return render_template('addHourse.html', username=username)
    else:
        cover = request.files.get('cover')
        # 42441eec-884a-4626-bd4d-3cb7ec6d72fc.jpg
        coverFileName = str(uuid.uuid4()) + '.' + cover.filename.replace('"', '').split('.')[-1]
        savePath = os.path.join(app.app.root_path, 'static', 'hourseImage', coverFileName)
        cover.save(savePath)

        createHourseInfo({
            'title': request.form.get('title'),
            'city': request.form.get('city'),
            'region': request.form.get('region'),
            'address': request.form.get('address'),
            'roomsDesc': request.form.get('roomsDesc'),
            'areaRange': request.form.get('areaRange'),
            'price': request.form.get('price'),
            'hourseDecoration': request.form.get('hourseDecoration'),
            'company': request.form.get('company'),
            'hourseType': request.form.get('hourseType'),
            'tags': request.form.get('tags'),
            'cover': 'http://localhost:5000/static/hourseImage/' + coverFileName
        })
        return redirect('/page/table')


@page_bp.route('/editHourse', methods=['GET', 'POST'])
def editHourse():
    username = session.get('username')
    if request.method == 'GET':
        id = request.args.get('id')
        hourseInfo = getHourseInfoById(id)
        return render_template('editHourse.html', username=username, hourseInfo=hourseInfo, hourseId=id)
    else:
        cover = request.files.get('cover')
        if cover:
            coverFileName = str(uuid.uuid4()) + '.' + cover.filename.replace('"', '').split('.')[-1]
            savePath = os.path.join(app.app.root_path, 'static', 'hourseImage', coverFileName)
            cover.save(savePath)
            coverUrl = 'http://localhost:5000/static/hourseImage/' + coverFileName
        else:
            coverUrl = ''

        id = request.args.get('id')
        editHourseInfoById({
            'title': request.form.get('title'),
            'city': request.form.get('city'),
            'region': request.form.get('region'),
            'address': request.form.get('address'),
            'roomsDesc': request.form.get('roomsDesc'),
            'areaRange': request.form.get('areaRange'),
            'price': request.form.get('price'),
            'hourseDecoration': request.form.get('hourseDecoration'),
            'company': request.form.get('company'),
            'hourseType': request.form.get('hourseType'),
            'tags': request.form.get('tags'),
            'cover': coverUrl
        }, id)
        return redirect('/page/table')


@page_bp.route('/removeHourse', methods=['GET', 'POST'])
def deleteHourse():
    id = request.args.get('id')
    if id:
        deleteHourseInfoById(id)
    return redirect('/page/table')


@page_bp.route('/hoursePriceChar', methods=['GET', 'POST'])
def getHoursePriceChar():
    username = session.get('username')

    cityList = getHourseCitysList()
    defaultCity = cityList[0]
    if request.args.get('city'):
        defaultCity = request.args['city']

    hourseData = getHourseInfoByCity(defaultCity)
    priceBarCloumn, priceRange = getCityBarChartData(hourseData)

    openDateLineCloumn, openDateLineAveragePrice = getOpenDateLineChartData(hourseData)

    scatterData = getTotalPriceChartData(hourseData)

    return render_template(
        'hoursePriceChar.html',
        username=username,
        cityList=cityList,
        cityName=defaultCity,
        priceBarCloumn=priceBarCloumn,
        priceRange=priceRange,
        openDateLineCloumn=openDateLineCloumn,
        openDateLineAveragePrice=openDateLineAveragePrice,
        scatterData=scatterData
    )


@page_bp.route('/hourseDetailChar', methods=['GET', 'POST'])
def getHourseDetailChar():
    username = session.get('username')

    hourseData = getAllHourseInfo()

    cityList = getHoursePriceCharCitysList(hourseData)

    priceChartData = getHourseDetailChartData(hourseData)

    defaultType = request.args.get('type')
    if not defaultType:
        defaultType = 'small'

    # areaChartColumn, areaChartData = getHourseAreaChartData(hourseData, defaultType)
    areaChartColumn, areaChartData = [], []

    return render_template(
        'hourseDetailChar.html',
        username=username,
        cityList=cityList,
        priceChartData=priceChartData,
        areaChartColumn=areaChartColumn,
        areaChartData=areaChartData,
    )


@page_bp.route('/hourseTypeChar', methods=['GET', 'POST'])
def getHourseTypeChar():
    username = session.get('username')

    cityList = getHourseCitysList()
    defaultCity = cityList[0]
    if request.args.get('city'):
        defaultCity = request.args['city']

    hourseData = getHourseInfoByCity(defaultCity)

    hourseDecoration = getHourseDecorationChartData(hourseData)

    hourseTypeChartData = getHourseTypeChartData(hourseData)

    return render_template(
        'hourseTypeChar.html',
        username=username,
        cityList=cityList,
        hourseDecoration=hourseDecoration,
        hourseTypeChartData=hourseTypeChartData,
    )


@page_bp.route('/hourseOtherChar', methods=['GET', 'POST'])
def getHourseOtherChar():
    username = session.get('username')

    return render_template(
        'hourseOtherChar.html',
        username=username,
    )


@page_bp.route('/companyWordCloud', methods=['GET', 'POST'])
def getHourseCompanyWordCloud():
    username = session.get('username')

    return render_template(
        'companyWordcloud.html',
        username=username,
    )


@page_bp.route('/tagsWordCloud', methods=['GET', 'POST'])
def getHourseTagsWordCloud():
    username = session.get('username')

    return render_template(
        'tagsWordcloud.html',
        username=username,
    )


@page_bp.route('/pricePrediction', methods=['GET', 'POST'])
def hoursePricePrediction():
    username = session.get('username')

    predResult = 0
    if request.method == 'GET':
        cityList = getHourseCitysList()
        return render_template(
            'hoursePricePrediction.html',
            username=username,
            cityList=cityList,
            predResult=predResult
        )
    else:
        print(request.form)
        saleStatus = request.form.get('status')

        if saleStatus == '在售':
            mostSaleStatus = 1
        elif saleStatus == '已售':
            mostSaleStatus = 2
        elif saleStatus == '出租中':
            mostSaleStatus = 3
        elif saleStatus == '已出租':
            mostSaleStatus = 4
        elif saleStatus == '预售':
            mostSaleStatus = 5
        else:
            mostSaleStatus = 6

        pass
        return 'POST'



